package com.google.gwt.livinglife.client;

import java.util.Iterator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.livinglife.client.data.ChallengeData;
import com.google.gwt.livinglife.client.data.LivingLifeGroupData;
import com.google.gwt.livinglife.client.data.UserIdData;
import com.google.gwt.livinglife.client.widgets.BasicPostBox;
import com.google.gwt.livinglife.client.widgets.ChallengeEntryForm;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class GroupDataPanel extends VerticalPanel {
	HTML group_name = new HTML();
	Label description_text = new Label();
	HTML members_label = new HTML("<h3>Members</h3>");
	HTML moderators_label = new HTML("<h3>Moderators</h3>");
	HorizontalPanel members_challenges = new HorizontalPanel();
	VerticalPanel recent_challenges = new VerticalPanel();
	HTML recent_challenge_header = new HTML("<center><h3> Recent challenges for the group</h3></center>"); 
	VerticalPanel group_members_list = new VerticalPanel();
	Button joinButton = new Button("Join Group");
	Button delete_group_button = new Button("delete group");
	
	DecoratedPopupPanel joiningPopup = new DecoratedPopupPanel();
	Long group_id = null;
	
	HorizontalPanel search_container = new HorizontalPanel();
	TextBox search_group_box = new TextBox();
	Button search_group_button = new Button("Find Groups");
	HTML post_challenge = new HTML("<h3>Post a challenge to this group</h3>");
	ChallengeEntryForm challenge_entry_form = new ChallengeEntryForm();
	
	public GroupDataPanel() {
		search_container.setHorizontalAlignment(ALIGN_RIGHT);
		search_container.add(search_group_box);
		search_container.add(search_group_button);
		add(search_container);
		super.add(group_name);
		group_name.setHeight("20px");
		super.add(description_text);
		// TODO: find out if current user is a member of this group or not, and show join button or
		// post challenge_form accordingly.
		super.add(joinButton);
		super.add(delete_group_button);
		super.add(post_challenge);
		super.add(challenge_entry_form);
		joiningPopup.setWidth("150px");
		joiningPopup.setWidget(new HTML("Processing join request"));
		search_group_button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				LivingLifeServiceAsync service =  GWT.create(LivingLifeService.class);
				try {
					service.getGroupByName(search_group_box.getText(), new AsyncCallback<LivingLifeGroupData>() {
						@Override
						public void onFailure(Throwable caught) {
							showGroupNotFound(search_group_box.getText());
						}
						@Override
						public void onSuccess(LivingLifeGroupData result) {
							showGroupData(result);
						}
					});
				} catch (ObjectNotFoundException e) {
					showGroupNotFound(search_group_box.getText());
				}
			}
			
		});
		joinButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if (group_id != null) {
					Widget source = (Widget) event.getSource();
          int left = source.getAbsoluteLeft() + 10;
          int top = source.getAbsoluteTop() + 10;
          joiningPopup.setPopupPosition(left, top);
					joiningPopup.show();
					LivingLifeServiceAsync service =  GWT.create(LivingLifeService.class);
					try {
						Window.alert("adding user " + LivingLife.getLogin_info().getUser_data().getId() + " to group " + group_id);
						service.addUserToGroup(LivingLife.getLogin_info().getUser_data().getId(), group_id, new AsyncCallback<Void>() {
							@Override
							public void onFailure(Throwable caught) {
								Window.alert("Could not add you to the group. Please try at a later time.");
							}
							@Override
							public void onSuccess(Void result) {
							}
						});
					} catch (NotLoggedInException e) {
						Window.alert("Could not add you to the group. Please try at a later time.");
					} finally {
						joiningPopup.hide();
					}
				}
			}
		});
		delete_group_button.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if (group_id == null) {
					return;
				}
				LivingLifeServiceAsync service = GWT.create(LivingLifeService.class);
				try {
					service.deleteGroup(group_id, new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							handleError(caught);
						}

						@Override
						public void onSuccess(Void result) {
							clear();
						}
					});
				} catch (Exception e) {
					
				}
			}
			
		});
		super.add(new HTML("<hr />"));
		super.add(members_challenges);
		members_challenges.setSpacing(5);
		members_challenges.add(group_members_list);
		Image line = new Image("clear.cache.gif");
		line.setWidth("3px");
		line.setHeight("300px");
		members_challenges.add(line);
		members_challenges.add(recent_challenges);
	}
	public void showGroupData(LivingLifeGroupData group_data) {
		group_id = group_data.getId();
		challenge_entry_form.setGroup_id(group_id);
		challenge_entry_form.setGroup_name(group_data.getName());
		group_name.setHTML("<h3>" + group_data.getName() + "</h3>");
		description_text.setText(group_data.getDescription());
		group_members_list.clear();
		group_members_list.add(members_label);
		Iterator<UserIdData> iterator = group_data.getMembers().iterator();
		String current_user_id = LivingLife.getLogin_info().getUser_data().getId();
		while(iterator.hasNext()) {
			UserIdData u = iterator.next();
			Anchor user_anchor = new Anchor(u.getNickname(), LivingLife.getUserIdUrl(u.getId()));
			group_members_list.add(user_anchor);
			if (u.getId().equals(current_user_id)) {
				joinButton.setVisible(false);
			}
		}
		group_members_list.add(moderators_label);
		iterator = group_data.getModerators().iterator();
		while(iterator.hasNext()) {
			UserIdData u = iterator.next();
			Anchor user_anchor = new Anchor(u.getNickname(), LivingLife.getUserIdUrl(u.getId()));
			group_members_list.add(user_anchor);
			if (u.getId().equals(current_user_id)) {
				
			}
		}
		
		recent_challenges.add(recent_challenge_header);
		LivingLifeServiceAsync service = GWT.create(LivingLifeService.class);
		try {
			ChallengeSelector selector = new ChallengeSelector();
			selector.setGroup_id(group_id);
			selector.setEnd_index(5);
			selector.setOrder(ChallengeSelector.SortOrder.TIME);
			service.getChallenges(selector, new AsyncCallback<ChallengeData[]>(){
				@Override
				public void onFailure(Throwable caught) {
					handleError(caught);
				}

				@Override
				public void onSuccess(ChallengeData[] result) {
					if (result != null) {
						for (int i = 0; i < result.length; ++i) {
							BasicPostBox post = new BasicPostBox();
							post.draw(result[i]);
							recent_challenges.add(post);
						}
					}
				}
				
			});
		} catch (Exception e) {
			handleError(e);
		}
	}
	
	protected void handleError(Throwable caught) {
		Window.alert("Encountered network error while fetching recent challenges for this group");
	}
	private void showGroupNotFound(String group_name) {
		super.clear();
		super.add(search_group_box);
		super.add(search_group_button);
		super.add(new HTML("Group " + group_name + " not found"));
	}
}
